import requests
import uuid
from fastapi import HTTPException
from app.config import settings
from app.database.models.chat import MessageRole

class AIService:
    """AI服务类，用于与豆包AI模型交互"""
    
    @staticmethod
    def get_ai_response(messages: list) -> str:
        """
        调用豆包AI模型获取响应
        
        参数:
            messages: 聊天历史消息列表，格式为[{"role": "user|ai|system", "content": "消息内容"}]
        
        返回:
            AI生成的响应内容
        """
        if not settings.DOUBAO_API_KEY:
            raise HTTPException(
                status_code=500,
                detail="豆包API密钥未配置，请检查环境变量"
            )
        
        # 构建请求参数
        payload = {
            "model": settings.DOUBAO_MODEL,
            "messages": messages,
            "temperature": 0.7,  # 控制生成内容的随机性
            "max_tokens": 1024   # 最大生成 tokens 数
        }
        
        # 设置请求头
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {settings.DOUBAO_API_KEY}"
        }
        
        try:
            # 调用豆包API
            response = requests.post(
                settings.DOUBAO_API_URL,
                json=payload,
                headers=headers,
                timeout=30  # 设置超时时间
            )
            
            # 检查响应状态
            response.raise_for_status()
            
            # 解析响应内容
            result = response.json()
            return result["choices"][0]["message"]["content"]
            
        except requests.exceptions.RequestException as e:
            # 处理请求异常
            raise HTTPException(
                status_code=500,
                detail=f"调用AI服务失败: {str(e)}"
            )
    
    @staticmethod
    def format_message(role: MessageRole, content: str) -> dict:
        """格式化消息为AI模型所需的格式"""
        return {
            "role": role.value,
            "content": content
        }
    
    @staticmethod
    def generate_message_id() -> str:
        """生成唯一消息ID"""
        return str(uuid.uuid4())
